package com.gs.view.riepilogo;

import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.gs.R;
import com.gs.business.cache.CacheGruppi;
import com.gs.domain.Gruppi;
import com.gs.view.impostazioni.GruppiView;
import comi.gsi.view.MyBaseActivity;

public class ListaGruppi extends MyBaseActivity {

	@Override
	protected int getIdLayout() {
		return R.layout.listattivita;
	}

	@Override
	protected void myOnCreate(final Bundle savedInstanceState) {

		Vector<Gruppi> groups = CacheGruppi.getSingleton().getVettoreGruppi();
		ArrayAdapter<Gruppi> adapter = new ArrayAdapter<Gruppi>(this, R.layout.rowgruppo, groups.toArray(new Gruppi[groups.size()])) {
			@Override
			public View getView(final int position, View convertView, final ViewGroup parent) {
				ViewHolder viewHolder = null;
				if (convertView == null) {
					final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					convertView = inflater.inflate(R.layout.rowgruppo, null);
					viewHolder = new ViewHolder();
					convertView.setTag(viewHolder);
				} else {
					viewHolder = (ViewHolder) convertView.getTag();
				}
				final Gruppi gruppo = getItem(position);
				getListNome(viewHolder, convertView).setText(gruppo.getNomeEntita() != null ? gruppo.getNomeEntita() : "NO");
				getListDescrizione(viewHolder, convertView).setText(gruppo.getdescrizione() != null ? gruppo.getdescrizione() : "NO");
				convertView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(final View v) {

						final Intent i = new Intent(ListaGruppi.this, GruppiView.class);
						i.putExtra("idGruppo", gruppo.getidGruppo());
						try {
							startActivity(i);
						} catch (final Exception e) {
							Log.e("boh", e.getMessage());
						}

					}
				});

				return convertView;
			}

			private TextView getListNome(final ViewHolder viewHolder, final View convertView) {
				if (viewHolder.listNomeTrs == null && convertView != null) {
					viewHolder.listNomeTrs = (TextView) convertView.findViewById(R.id.listaGruppoNome);
				}
				return viewHolder.listNomeTrs;
			}

			private TextView getListDescrizione(final ViewHolder viewHolder, final View convertView) {
				if (viewHolder.listDescrTrs == null && convertView != null) {
					viewHolder.listDescrTrs = (TextView) convertView.findViewById(R.id.listaGruppoDescr);
				}
				return viewHolder.listDescrTrs;
			}
		};

		ListView list = (ListView) findViewById(R.id.listView1);
		list.setAdapter(adapter);

	}

	private static class ViewHolder {
		public TextView listNomeTrs;
		public TextView listDescrTrs;
	}
}
